<?php

namespace app\admin\controller\wx;

use app\common\controller\Backend;

use think\Controller;
use think\Request;
use think\Db;

/**
 * @icon fa fa-circle-o
 */
class Type extends Backend
{
    /**
     * Type模型对象
     */
    protected $model = null;
    protected $searchFields = 'type_name';
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Type');

    }
    
    private function icon(){
        $icons = array();
        for($i = 1; $i <= 8; $i++){
            $icons[$i]['path'] = config('iconpath') . '/' . $i . '.png';
            $icons[$i]['title'] = $i;
        }
        return $icons;
    }
    /**
     * 查看
     */
    public function index(){
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $where = array();
            $where['is_delete'] = array('eq', 0);
            $where['category'] = array('eq', 1);
            
            $inputData = input();
            $filter = json_decode($inputData['filter'], true);

            if(!empty($filter['type_name'])) {
                $where['type_name'] = array('like', "%{$filter['type_name']}%");
            }
            if(!empty($filter['kind'])) {
                $where['kind'] = array('eq', $filter['kind']);
            }
            
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            
            foreach($list as &$v) {
                $v['is_delete'] = $v['is_delete']==0?'显示':'不显示';
                switch ($v['kind']) {
                    case  'information':
                        $v['kind'] = '信息类';
                        break;
                    case 'mission':
                        $v['kind'] = '任务类';
                        break;
                    case 'info_mission':
                        $v['kind'] = '任务信息类';
                        break;
                    default:
                        $v['kind'] = '未设置';
                        break;
                }
                $v['click_pay'] = $v['click_pay']==1?'可以':'不可以';
                $v['see_pay'] = $v['see_pay']==1?'可以':'不可以';
                $v['cash_deposit'] = $v['cash_deposit']==1?'可以':'不可以';
                $v['offer_reward'] = $v['offer_reward']==1?'可以':'不可以';
                //$v['transpond_pay'] = $v['transpond_pay']==1?'可以':'不可以';
            }
            
            $result = array("total" => $total, "rows" => $list);
            //echo $this->model->getLastSql();
            return json($result);
        }
        
        //设置列表工具栏
        $btns = array('refresh', 'add');
        
        $typeModel = model('Type');
        $kinds = $typeModel::$info_kind;
        $kinds = json_encode($kinds, JSON_UNESCAPED_UNICODE);
        $this->view->assign('kinds', $kinds);
        $this->view->assign('btns', $btns);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add(){
        
        if ($this->request->isPost()) {
            $type_name = input('type_name');
            $type_tpl = input('type_tpl');
            $kind = input('kind');
            $click_pay = input('click_pay');
            $see_pay = input('see_pay');
            $cash_deposit = input('cash_deposit');
            $offer_reward = input('offer_reward');
            
            if(empty($type_name)){
                $this->error("信息分类名称不能为空");
            }
            $add_data = array(
                'type_name' => $type_name,
                'type_tpl' => $type_tpl,
                'kind' => $kind,
                'click_pay' => $click_pay,
                'see_pay' => $see_pay,
                'cash_deposit' => $cash_deposit,
                'offer_reward' => $offer_reward,
                'category' => 1,
                'update_time' => time()
            );
    
            // 插入单个记录
            Db::name('type')->insert($add_data);
            /*echo $this->model->getLastSql();
            exit;*/
            // 获取上次写入的自增Id
            $type_id = Db::getLastInsID();
            
            if(empty($type_id)){
                $this->error("添加失败");
            }
            $inputData = input();
            $type_num = isset($inputData['type_num'])?$inputData['type_num']:[];
            $option_name = isset($inputData['option_name'])?$inputData['option_name']:[];
            $letter = isset($inputData['letter'])?$inputData['letter']:[];
            $option_type = isset($inputData['option_type'])?$inputData['option_type']:[];
            $data_list = isset($inputData['data_list'])?$inputData['data_list']:[];
            $is_show_name = isset($inputData['is_show_name'])?$inputData['is_show_name']:[];
            $is_must = isset($inputData['is_must'])?$inputData['is_must']:[];
            $option_holder = isset($inputData['option_holder'])?$inputData['option_holder']:[];
            $option_notes = isset($inputData['option_notes'])?$inputData['option_notes']:[];
            $is_self = isset($inputData['is_self'])?$inputData['is_self']:[];
            $self_suffix = isset($inputData['self_suffix'])?$inputData['self_suffix']:[];
            $detail_show = isset($inputData['detail_show'])?$inputData['detail_show']:[];
            $icon = isset($inputData['icon'])?$inputData['icon']:[];
            $pay_connect = isset($inputData['pay_connect'])?$inputData['pay_connect']:[];
            //$is_interest = $inputData['is_interest'];
    
            $option_id_arr = array();
            
            $OptionModel = Db::name('option');
            
            $error = "";
    
            foreach($type_num as $k=>$v){
                $a = $k+1;
                if(empty($option_name[$k])){
                    $error = "请选填写信息【".$a."】的名称";
                    break;
                }
                if((empty($option_type[$k]) && $option_type[$k] != "0") || !isset($option_type[$k])){
                    $error = "请选择信息【".$a."】的类型";
                    break;
                }
                if(in_array($option_type[$k],array(2,3)) && empty($data_list[$k])){
                    $error = "请填写信息【".$a."】的选项";
                    break;
                }
            }
            if(!empty($error)){
                $this->error($error);
            }

            $ListModel = Db::name('option_list');
            
            foreach($type_num as $key=>$num){
                $data = array();
                $data['type_id'] = $type_id;
                $data['num'] = $num;
                $data['option_name'] = $option_name[$key];
                $data['letter'] = $letter[$key];
                $data['option_type'] = $option_type[$key];
        
                $data['is_show_name'] = isset($is_show_name[$key])?$is_show_name[$key] : 1;
                $data['is_must'] = isset($is_must[$key])?$is_must[$key]:0;
                $data['option_holder'] = isset($option_holder[$key])?$option_holder[$key] : '';
                $data['option_notes'] = isset($option_notes[$key])?$option_notes[$key] : "";
                $data['is_self'] = isset($is_self[$key])?$is_self[$key] : 0;
                $data['self_suffix'] = isset($self_suffix[$key])?$self_suffix[$key] : "";
                $data['detail_show'] = isset($detail_show[$key])?$detail_show[$key]:0;
                $data['pay_connect'] = isset($pay_connect[$key])?$pay_connect[$key]:0;
                $data['icon'] = isset($icon[$key])?$icon[$key]:1;
                //$data['is_interest'] = $is_interest?$is_interest:0;

                if(empty($option_id_arr[$key])){
                    $OptionModel->insert($data);
                    $data['option_id'] = Db::getLastInsID();
                }
                else{
                    $data['option_id'] = $option_id_arr[$key];
                    $OptionModel->update($data);
                    $ListModel->where('option_id', $data['option_id'])->delete();
                }
                if(in_array($data['option_type'],array(2,3))){
                    $list_array = explode("|",$data_list[$key]);
                    $option_list = array();
                    foreach($list_array as $name){
                        $option_list[] = array("option_id"=>$data['option_id'],"list_name"=>$name, 'is_interest' => 1);
                    }
                    $ListModel->insertAll($option_list);
                }
            }
            $option_del = input("del_option");
            if(!empty($option_del) && is_array($option_del)){
                $OptionModel->where('option_id', 'in', $option_del)->update(['is_delete' => 1]);
            }
            $this->success("操作成功");
        } else {
            $this->view->assign('option_count', 0);
            $this->view->assign('option_list', array());
        }
        $this->view->assign('icons', $this->icon());
        $icons_json = json_encode(array_values($this->icon()));
        $this->view->assign('icons_json', $icons_json);
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $type_id = $ids;
        $type_info = Db::name('type')->where(array("is_delete" => 0,"type_id" => $type_id))->find();

        $option_list = Db::name('option')->where(array("is_delete" => 0,"type_id" => $type_id))->order("num ASC,option_id ASC")->select();

        foreach($option_list as  $key=>$val){
            $data_list = Db('option_list')->where(array("option_id" => $val['option_id']))->column("list_name");
            if(!empty($data_list)){
                $option_list[$key]['data_list'] = implode("|",$data_list);
            }
        }
        $option_count = Db::name('option')->where(array("type_id"=>$type_id))->max("num");
        $option_count = $option_count ? $option_count : 0;

        $this->view->assign("option_count",$option_count);
        $this->view->assign("type_info",$type_info);
        $this->view->assign("option_list",$option_list);

        if ($this->request->isPost()) {
            //分类下有文章的不能修改
            $exist =  Db::name('amoy')->where('type_id', $type_id)->find();
            if($exist) {
                $this->error("该分类下已经有文章, 不能修改模版");
            }

            $type_name = input('type_name');
            $type_tpl = input('type_tpl');
            $kind = input('kind');
            $click_pay = input('click_pay');
            $see_pay = input('see_pay');
            $cash_deposit = input('cash_deposit');
            $offer_reward = input('offer_reward');
            if(empty($type_name)){
                $this->error("信息分类名称不能为空");
            }
            if($type_id){
                $save_data = array(
                    'type_name' => $type_name,
                    'type_tpl' => $type_tpl,
                    'kind' => $kind,
                    'click_pay' => $click_pay,
                    'see_pay' => $see_pay,
                    'cash_deposit' => $cash_deposit,
                    'offer_reward' => $offer_reward,
                    'category' => 1,
                    'update_time' => time()
                );
                Db::name('type')->where(array("is_delete" => 0,"type_id" => $type_id))->update($save_data);
            }

            if(empty($type_id)){
                $this->error("添加失败");
            }

            $inputData = input();
            $type_num = isset($inputData['type_num'])?$inputData['type_num']:[];
            $option_name = isset($inputData['option_name'])?$inputData['option_name']:[];
            $letter = isset($inputData['letter'])?$inputData['letter']:[];
            $option_type = isset($inputData['option_type'])?$inputData['option_type']:[];
            $data_list = isset($inputData['data_list'])?$inputData['data_list']:[];
            $is_show_name = isset($inputData['is_show_name'])?$inputData['is_show_name']:[];
            $is_must = isset($inputData['is_must'])?$inputData['is_must']:[];
            $option_holder = isset($inputData['option_holder'])?$inputData['option_holder']:[];
            $option_notes = isset($inputData['option_notes'])?$inputData['option_notes']:[];
            $is_self = isset($inputData['is_self'])?$inputData['is_self']:[];
            $self_suffix = isset($inputData['self_suffix'])?$inputData['self_suffix']:[];
            $detail_show = isset($inputData['detail_show'])?$inputData['detail_show']:[];
            $icon = isset($inputData['icon'])?$inputData['icon']:[];
            $pay_connect = isset($inputData['pay_connect'])?$inputData['pay_connect']:[];
            //$is_interest = $inputData['is_interest'];

            $option_id_arr = isset($inputData['option_id'])?$inputData['option_id']:0;
            $OptionModel = Db::name('option');

            $error = "";

            foreach($type_num as $k=>$v){
                $a = $k+1;
                if(empty($option_name[$k])){
                    $error = "请选填写信息【".$a."】的名称";
                    break;
                }
                if(empty($option_type[$k]) && $option_type[$k] != "0"){
                    $error = "请选择信息【".$a."】的类型";
                    break;
                }
                if(in_array($option_type[$k],array(2,3)) && empty($data_list[$k])){
                    $error = "请填写信息【".$a."】的选项";
                    break;
                }
            }
            if(!empty($error)){
                $this->error($error);
            }

            $ListModel = Db::name('option_list');
            foreach($type_num as $key=>$num){
                $data = array();
                $data['type_id'] = $type_id;
                $data['num'] = $num;
                $data['option_name'] = $option_name[$key];
                $data['letter'] = $letter[$key];
                $data['option_type'] = $option_type[$key];

                $data['is_show_name'] = isset($is_show_name[$key]) ? $is_show_name[$key] : 1;
                $data['is_must'] = isset($is_must[$key])? $is_must[$key] : 0;
                $data['option_holder'] = isset($option_holder[$key])?$option_holder[$key] : '';
                $data['option_notes'] = isset($option_notes[$key])?$option_notes[$key] : "";
                $data['is_self'] = isset($is_self[$key])?$is_self[$key] : 0;
                $data['self_suffix'] = isset($self_suffix[$key])?$self_suffix[$key] : "";
                $data['detail_show'] = isset($detail_show[$key])?$detail_show[$key]:0;
                $data['pay_connect'] = isset($pay_connect[$key])?$pay_connect[$key]:0;
                $data['icon'] = isset($icon[$key])?$icon[$key]:1;
                //$data['is_interest'] = $is_interest?$is_interest:0;

                if(empty($option_id_arr[$key])){
                    $OptionModel->insert($data);
                    $data['option_id'] = Db::getLastInsID();
                } else {
                    $data['option_id'] = $option_id_arr[$key];
                    $OptionModel->update($data);
                    $ListModel->where('option_id', $data['option_id'])->delete();
                }

                if(in_array($data['option_type'],array(2,3))){
                    $list_array = explode("|",$data_list[$key]);
                    $option_list = array();
                    foreach($list_array as $name){
                        $option_list[] = array("option_id"=>$data['option_id'], "list_name"=>$name, 'is_interest' => 1);
                    }
                    $ListModel->insertAll($option_list);
                }
            }

            if(isset($inputData['del_option'])) {
                $option_del = $inputData['del_option'];
                if(!empty($option_del) && is_array($option_del)){
                    $OptionModel->where('option_id', 'in', $option_del)->update(['is_delete' => 1]);
                }
            }

            $this->success("操作成功");
        }

        $this->view->assign('icons', $this->icon());
        $icons_json = json_encode(array_values($this->icon()));
        $this->view->assign('icons_json', $icons_json);
        return $this->view->fetch();
    }
    /**
     * 删除
     */
    public function del($ids = ""){
        $type_id = $ids;
        $status = Db::name('type')->where(array("type_id" => $type_id))->update(array("is_delete"=>1));
        if($status){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
    /**
     * 兴趣点管理
     * @author 石榴的石
     * @date 2018.01.29
     */
    public function interest_list($ids = ""){
        $type_id = $ids;
        $where = array();
        $where['t.type_id'] = array('eq', $type_id);
        $list = Db::name('type')
            ->alias('t')
            ->join('cy_option o', 't.type_id = o.type_id')
            ->join('cy_option_list ol', 'o.option_id = ol.option_id')
            ->field('ol.list_id, t.type_name, o.option_name, ol.list_name, ol.is_interest')
            ->where($where)
            ->order('ol.list_id ASC')
            ->paginate(10);

        $list->render();
        $this->view->assign('list', $list);
        return $this->view->fetch();
    }
    /**
     * 更改兴趣点状态
     * @author 石榴的石
     * @date 2018.01.29
     */
    public function change_interest(){
        $list_id = input('id', 0, 'intval');
        $status = input('status', 0, 'intval');
        $is_interest = $status==0?1:0;
        $re = Db::name('option_list')->where(array('list_id' => $list_id))->update(array('is_interest' => $is_interest));

        if($re !== false) {
            return ['error' => 200, 'message' => 'success'];
        } else {
            return ['error' => 500, 'message' => 'fail'];
        }
    }

    public function test_ajax(){
        //echo json_encode(['message' => 1]);
        //$this->success('message');
        return ['error' => 200, 'message' => 'success'];
    }
}
